package core.form;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class StrutsXml {

	public static Map<String, XmlBean> struts_xml(String strtuts_path) throws JDOMException, IOException{
		//解析.xml文件
		SAXBuilder builder  = new SAXBuilder();
		Document document = builder.build(new File(strtuts_path));
		//获得根节点目录
		Element root  = document.getRootElement();
		Map<String, XmlBean> rmap = new HashMap<String, XmlBean>();
		
		Element actionRoot = root.getChild("action-mapping");
		List<Element> actionMaping = actionRoot.getChildren();
		for (Element elementAction : actionMaping) {
			XmlBean action = new XmlBean();
			String name = elementAction.getAttributeValue("name");
			action.setBean(name);
			Element actionForm = root.getChild("formbeans");
			List<Element> form = actionForm.getChildren();
			for (Element element : form) {
				if(name.equals(element.getAttributeValue("name"))){
					String formclass = element.getAttributeValue("class");
						action.setFormClass(formclass);
						break;
				}
			}
				String path = elementAction.getAttributeValue("path");
				action.setPath(path);
				String type = elementAction.getAttributeValue("type");
				action.setActionType(type);
				List<Element> forward  = elementAction.getChildren();
				Map<String, String> map = new HashMap<String, String>();
				for (Element x : forward) {
					String name1 = x.getAttributeValue("name");
					String value1 = x.getAttributeValue("value");
					map.put(name1, value1);
				}
				action.setActionForward(map);
				rmap.put(path, action);
				
			}
		return rmap;
			
	}
	public static void main(String[] args) throws JDOMException, IOException {
		String path = "WebRoot/WEB-INF/struts-config.xml";
		Map<String,XmlBean> m = new StrutsXml().struts_xml(path);
		Set<String> keySet = m.keySet();
		for (Iterator<String> it =  keySet.iterator();it.hasNext();) {
			String key = it.next();
			System.out.println(key);
			System.out.println(m.get(key));
		}
		
		
	}
}
